package zlogs

import (
	"fmt"
	"strings"
	"time"
	"gitee.com/zouyang8210/zfile"
)

const (
	logs = "logs"
)

type Color uint8

const (
	BLACK   Color = iota + 30 // 黑色
	RED                       // 红色
	GREEN                     // 绿色
	YELLOW                    // 黄色
	BLUE                      // 蓝色
	MAGENTA                   // 紫红色
	CYAN                      // 青蓝色
	WHITE                     // 白色
)

// WriteLogs 写文件日志
func WriteLogs(dir string, s string, v ...interface{}) (b bool) {
	if !zfile.DirExists(logs) {
		b = zfile.CreateDirectory(logs)
	}
	devDir := logs + "/" + dir
	if !zfile.DirExists(devDir) {
		b = zfile.CreateDirectory(devDir)
	}
	strNow := time.Now()

	filePath := devDir + "/" + strNow.Format(time.DateOnly)
	txtLog := fmt.Sprintf("%s->%s\n", strNow.Format(time.TimeOnly), s)
	if v != nil {
		txtLog += fmt.Sprintf("%#v\n", v)
	}
	b = zfile.WriteTextFile(filePath, txtLog)
	return
}

// Error 打印错误日志
func Error(msg string) {
	fmt.Println(colorRender(now()+msg, RED, false, false))
}

// Msg 打印日志
func Msg(msg string) {
	fmt.Println(colorRender(now()+msg, CYAN, false, false))
}

func colorRender(str string, color Color, bold, underLine bool) string {
	var mo []string
	if underLine { //下划线效果
		mo = append(mo, "04")
	}
	if bold { //加粗字体
		mo = append(mo, fmt.Sprintf("%d", 1))
	}
	if len(mo) <= 0 {
		mo = append(mo, "0")
	}
	return fmt.Sprintf("\033[%s;%dm"+str+"\033[0m", strings.Join(mo, ";"), color)
}

func now() string {
	strNow := time.Now().Format(time.DateTime)
	strNow += "->"
	return strNow
}
